package com.read.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.read.clients.OrderClients;
import com.read.config.RedisKey;
import com.read.entity.Book;
import com.read.entity.BookChapter;
import com.read.entity.Order;
import com.read.mapper.BookChapterMapper;
import com.read.resp.BaseResp;
import com.read.service.BookChapterService;
import com.read.service.BookService;
import com.read.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName BookDetailServiceImpl
 * @Description TODO
 * @Author young
 * @Date 2022-11-05 15:01
 * @Version 1.0
 **/
@Service
public class BookChapterServiceImpl extends ServiceImpl<BookChapterMapper, BookChapter> implements BookChapterService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    BookChapterMapper bookChapterMapper;
    @Autowired
    BookService bookService;
    @Autowired
    BookServiceImpl bookServiceImpl;
    @Autowired
    OrderClients orderClients;


    @Override
    public BaseResp findChaptersByBookId(String bookId) {
        Boolean aBoolean = redisTemplate.boundHashOps(RedisKey.BOOK_CHAPTER).hasKey(bookId);
        if (!aBoolean){
            List<BookChapter> chaptersByBookId = bookChapterMapper.findChaptersByBookId(bookId);
            if (chaptersByBookId!=null){
                redisTemplate.boundHashOps(RedisKey.BOOK_CHAPTER).put(bookId,chaptersByBookId);
            }else{
                redisTemplate.opsForValue().set(RedisKey.BOOK_CHAPTER,null,10, TimeUnit.SECONDS);
            }
        }
        Object o = redisTemplate.boundHashOps(RedisKey.BOOK_CHAPTER).get(bookId);
        return new BaseResp().Success("章节列表查询成功!",o,null);
    }

    @Override
    public BaseResp findContentByBookId(String bookId,Integer id, HttpServletRequest request) {
        BaseResp bookDetails = bookServiceImpl.getBookDetailsByBoodId(bookId);
        if (bookDetails.getData()==null) {
            return new BaseResp().Error("没有该图书!");
        }
            Object data = bookDetails.getData();
            Book book = JSONObject.parseObject(JSON.toJSONString(data), Book.class);
        //1 先判断当前书是免费的还是付费
            //1.1 如果是免费的
        if (book.getIsfree()==0){
            //1.1.1 查询redis中是否有该图书的缓存
            Boolean aBoolean = redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT + bookId).hasKey(id.toString());
            if (!aBoolean) {
                //如果redis中没有, 去数据库查询放置在redis中
                List<BookChapter> contentByBookId = bookChapterMapper.findContentByBookId(bookId);
                if (contentByBookId == null || contentByBookId.size()==0) {
                    return new BaseResp().Error("该免费图书暂未更新章节!");
                }
                for (BookChapter chapter : contentByBookId) {
                    redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT + bookId).put(chapter.getId().toString(),chapter.getContent());
                }
            }
            Object o = redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT + bookId).get(id.toString());
            return new BaseResp().Success("免费书当前章节查询成功!",o,null);
        }else{
            //1.2 如果是收费的图书
            //1.2.1 通过前端的request请求 获取到token(此时token是生成的 uuid)
            String token = request.getHeader("token");
            //1.2.2 以uuid为key,从redis中查询出 jwt token串   调用工具类对jwt进行解密,获取到userId
//            String userId = JWTUtils.verfiyTokenGetUserId(token);
            //1.2.3 查询redis中是否有该用户的该本付费书的缓存
            String userId = token;
            Boolean aBoolean = redisTemplate.boundHashOps(RedisKey.BOOK_CHAPTER + bookId+":"+userId).hasKey(id.toString());
            if (!aBoolean){
                //如果没有,远程调用order服务, 去数据库获取该用户 该本书 的订单信息
//                BaseResp ordersByUserId = orderClients.getOrdersByUserId(request, bookId);
//                Object data1 = ordersByUserId.getData();
//                Order order = JSON.parseObject(JSON.toJSONString(data1), Order.class);
//                //如果订单信息为null,证明该用户没有付费购买任何书,返回试看内容
//                if (order==null){
//                    return new BaseResp().Error("此书为付费图书,请先付费!");
//                }
                //如果订单信息不为null,证明用户买了这本书,但是还没看过,去数据库查询,将查询结果放置在redis中建立缓存
                    //通过bookId 查询到该书的所有章节列表 信息
                List<BookChapter> contentByBookId = bookChapterMapper.findContentByBookId(bookId);
                if (contentByBookId == null || contentByBookId.size()==0) {
                    return new BaseResp().Error("该付费图书暂未更新章节!");
                }
                //循环章节列表信息,查询出每一个章节的内容,放置在redis中
                for (BookChapter chapter : contentByBookId) {
                    redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT+bookId+":"+userId).put(chapter.getId().toString(),chapter.getContent());
                }

            }
            Object o = redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT + bookId + ":" + userId).get(id.toString());
            return new BaseResp().Success("付费书当前章节内容查询成功!",o,null);
        }
    }

    @Override
    public BaseResp findPreContentById(String bookId, Integer id, HttpServletRequest request) {

        String token = request.getHeader("token");
        //1.2.2 以uuid为key,从redis中查询出 jwt token串   调用工具类对jwt进行解密,获取到userId
//        String userId = JWTUtils.verfiyTokenGetUserId(token);
        String userId = token;

        Object o = redisTemplate.boundHashOps(RedisKey.BOOK_DETAILS).get(bookId);
        Book book = JSONObject.parseObject(JSON.toJSONString(o), Book.class);
        Integer pre = id-1;
        if (book.getIsfree()==0){
            //如果是免费的书  redis中存储是 k+bookid   id
            Object o1 = redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT + bookId).get(pre.toString());
            if (o1==null){
                return new BaseResp().Error("此处是第一章!");
            }
            return new BaseResp().Success("上一章查询成功!",o1,null);

        }else{
            //如果是收费的书  redis中存储是 k+userid:bookid    id
            Object o1 = redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT + bookId + ":" + userId).get(pre.toString());
            if (o1==null){
                return new BaseResp().Error("此处是第一章!");
            }
            return new BaseResp().Success("上一章查询成功!",o1,null);
        }

    }

    @Override
    public BaseResp findNextContentById(String bookId, Integer id, HttpServletRequest request) {
        String token = request.getHeader("token");
        //1.2.2 以uuid为key,从redis中查询出 jwt token串   调用工具类对jwt进行解密,获取到userId
//        String userId = JWTUtils.verfiyTokenGetUserId(token);
        String userId = token;

        Object o = redisTemplate.boundHashOps(RedisKey.BOOK_DETAILS).get(bookId);
        Book book = JSONObject.parseObject(JSON.toJSONString(o), Book.class);
        Integer pre = id+1;
        if (book.getIsfree()==0){
            //如果是免费的书  redis中存储是 k+bookid   id

            Object o1 = redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT + bookId).get(pre.toString());
            if (o1==null){
                return new BaseResp().Error("此处是最后一章哦!");
            }
            return new BaseResp().Success("下一章查询成功!",o1,null);

        }else{
            //如果是收费的书  redis中存储是 k+userid:bookid    id
            Object o1 = redisTemplate.boundHashOps(RedisKey.BOOK_CONTENT + bookId + ":" + userId).get(pre.toString());
            if (o1==null){
                return new BaseResp().Error("此处是最后一章哦!");
            }
            return new BaseResp().Success("下一章查询成功!",o1,null);
        }
    }


}
